package com.binance.gateway.filter.auth;

import com.alibaba.fastjson.JSONObject;
import com.binance.gateway.app.base.helper.BaseHelper;
import com.binance.gateway.app.base.helper.SessionHelper;
import com.binance.gateway.app.constant.Constant;
import com.binance.gateway.constant.GwFilterOrders;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class TokenRenewFilter extends ZuulFilter {
    @Resource
    private SessionHelper sessionHelper;
    @Resource
    private BaseHelper baseHelper;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return GwFilterOrders.AUTH + 1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.get(Constant.AUTH_FILTER_RUN) == null;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        String token = baseHelper.getPnkToken(ctx.getRequest());
        if (StringUtils.isNotEmpty(token)) {
            // 若请求中包含token，则自动续期，避免pnk中的token有效，authcenter的却已失效，单pnk下线后，该filter就要废弃
            JSONObject session = sessionHelper.getAndRenewToken(token);
            if (session == null) {
                log.info("token is expire = {}", StringUtils.left(token, Constant.TOKEN_SHOW_LEN));
            }
        }
        return null;
    }
}
